//
//  YDNetClient.m
//  YiDao
//
//  Created by Demon on 2017/10/22.
//  Copyright © 2017年 Demon. All rights reserved.
//

#import "YDNetClient.h"

static YDNetClient *manager;

static NSString *const GETStr = @"GET";
static NSString *const POSTStr = @"POST";

static NSString *STATUS  = @"code";
static NSString *STATUSCODE = @"200";
static NSString *RESULT = @"data";

@implementation YDNetClient

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    _dispatch_once(&onceToken, ^{
        manager = [[self alloc] initWithBaseURL:nil];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain",@"text/html", nil];
        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        manager.requestSerializer.timeoutInterval = 30.f;
        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    });
    return manager;
}

- (void)getMethod:(NSString *)url param:(NSDictionary *)paramDic success:(SuccessBlock)successBlock fail:(FailBlock)failBlock {
    
    NSMutableString *absoluteUrl = [[NSMutableString alloc] initWithFormat:@"%@",url];
    if (paramDic) {
        NSArray *paramKeys = paramDic.allKeys;
        [absoluteUrl appendString:@"?"];
        int i = 0;
        for (NSString *key in paramKeys) {
            if (i == paramKeys.count - 1) {
                [absoluteUrl appendFormat:@"%@=%@",key,paramDic[key]];
            } else {
                [absoluteUrl appendFormat:@"%@=%@&",key,paramDic[key]];
            }
            i ++;
        }
    }
    UIAPPLICATION.networkActivityIndicatorVisible = YES;
    NSLog(@"url = %@\nparam = %@",absoluteUrl,[paramDic jsonPrettyStringEncoded]);
    NSString *URL = [absoluteUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [manager GET:URL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"successResult =\n%@\n\n%@",url,[(NSDictionary *)responseObject jsonPrettyStringEncoded]);
        NSString *code;
        if ([responseObject[STATUS] isKindOfClass:[NSNumber class]]) {
            code = [responseObject[STATUS] stringValue];
        } else {
            code = responseObject[STATUS];
        }
        if ([code isEqualToString:STATUSCODE]) {
            NSDictionary *result = responseObject[RESULT];
            successBlock(result);
        } else {
            NSError *error = [[NSError alloc] initWithDomain:@"返回错误" code:[responseObject[STATUS] integerValue] userInfo:responseObject];
            if (failBlock) failBlock(error);
        }
        
        UIAPPLICATION.networkActivityIndicatorVisible = NO;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failResult =\n%@\n \n%@",url,error);
        NSError *error1 = [self getError:error];
        if (failBlock) failBlock(error1);
        UIAPPLICATION.networkActivityIndicatorVisible = NO;
    }];
}

- (void)postMethod:(NSString *)url param:(NSDictionary *)paramDic success:(SuccessBlock)successBlock fail:(FailBlock)failBlock {
    NSMutableDictionary *mutableDic = [[NSMutableDictionary alloc] initWithDictionary:paramDic];
    
    NSString *postUrl = [NSString stringWithFormat:@"%@",url];
    NSLog(@"url = %@\nparam = %@",postUrl,[mutableDic jsonPrettyStringEncoded]);
    
    UIAPPLICATION.networkActivityIndicatorVisible = YES;
    [manager POST:postUrl parameters:mutableDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"successResult =\n%@\n\n%@",url,[(NSDictionary *)responseObject jsonPrettyStringEncoded]);
        NSString *code;
        if ([responseObject[STATUS] isKindOfClass:[NSNumber class]]) {
            code = [responseObject[STATUS] stringValue];
        } else {
            code = responseObject[STATUS];
        }
        if ([code isEqualToString:STATUSCODE]) {
            NSDictionary *result = responseObject[RESULT];
            successBlock(result);
        } else {
            NSError *error = [[NSError alloc] initWithDomain:@"返回错误" code:[responseObject[STATUS] integerValue] userInfo:responseObject];
            if (failBlock) failBlock(error);
        }
        UIAPPLICATION.networkActivityIndicatorVisible = NO;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failResult =\n%@\n \n%@",url,error);
        NSError *error1 = [self getError:error];
        if (failBlock) failBlock(error1);
        UIAPPLICATION.networkActivityIndicatorVisible = NO;
    }];
}

/**! 过滤错误码*/
- (NSError *)getError:(NSError *)error {
    NSError *error1;
    if ([error.userInfo.allKeys[0] isEqualToString:@"NSDebugDescription"] ||[error.userInfo.allKeys[0] isEqualToString:@"NSUnderlyingError"] ) {
        error1 = [[NSError alloc] initWithDomain:error.userInfo[@"NSDebugDescription"]?@"请检查接口路径":error.userInfo[@"NSLocalizedDescription"]?error.userInfo[@"NSLocalizedDescription"]:@"请求错误" code:404 userInfo:error.userInfo];
    } else {
        error1 = [[NSError alloc] initWithDomain:error.userInfo[@"NSLocalizedDescription"] code:(NSInteger)error.userInfo[@"_kCFStreamErrorCodeKey"] userInfo:error.userInfo];
    }
    return error1;
}

@end

